package com.dlc.felear.xiaoensale.helper;

import static com.dlc.felear.xiaoensale.constant.Constant.HOT_TEMP_MAX;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.DoubleInputDialog;
import com.dlc.felear.xiaoensale.customView.JbSelectDialog;
import com.dlc.felear.xiaoensale.customView.LoadingDialog;
import com.dlc.felear.xiaoensale.customView.PowerCcjdDialog;
import com.dlc.felear.xiaoensale.customView.PowerSelectDialog;
import com.dlc.felear.xiaoensale.customView.SingleInputDialog;
import com.dlc.felear.xiaoensale.dao.ActionStepItemDao;
import com.dlc.felear.xiaoensale.deviceControlSf.OperatorAutoHandle;
import com.dlc.felear.xiaoensale.entity.ActionStepItem;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.utils.HotModelUtil;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class ActionHelper implements Handler.Callback, SingleInputDialog.SingleDialogCallback,PowerSelectDialog.PowerSelectDialogCallback,
        PowerCcjdDialog.SelectCcjdDialogCallback,
        DoubleInputDialog.DoubleDialogCallback, HotModelUtil.HotModelUtilCallback, JbSelectDialog.JbSelectDialogCallback {
    private static final String TAG = "ActionHelper";
    private static final int WHAT_CANCEL_DIALOG = 343;
    private LoadingDialog loadingDialog;
    private Context context;
    private Handler handler;
    private SingleInputDialog singleInputDialog;
    private DoubleInputDialog doubleInputDialog;
    private TextView tvPower, tvTemp, tvError;
    private HotModelUtil hotModelUtil;
    private ActionStepItemDao actionStepItemDao;
    private List<Operator> recordOperaters = new ArrayList<>();
    private PowerSelectDialog powerSelectDialog;
    private JbSelectDialog jbSelectDialog;
    private PowerCcjdDialog powerCcjdDialog;


    public void setTvPower(TextView tvPower, TextView tvTemp, TextView tvError) {
        this.tvPower = tvPower;
        this.tvTemp = tvTemp;
        this.tvError = tvError;
    }

    public ActionHelper(Context context) {
        this.context = context;
        loadingDialog = new LoadingDialog(context, "正在执行");
        handler = new Handler(this);
        singleInputDialog = new SingleInputDialog(context, this);
        doubleInputDialog = new DoubleInputDialog(context, this);
        hotModelUtil = HotModelUtil.getInstance().setHotModelUtilCallback(this);
        actionStepItemDao = new ActionStepItemDao(context);
        powerSelectDialog=new PowerSelectDialog(context,this);
        jbSelectDialog=new JbSelectDialog(context,this);
        powerCcjdDialog=new PowerCcjdDialog(context,this);
    }

    /**
     * 分类处理点击动作
     *
     * @param type
     * @param item
     */
    public void parserAction(int type, ActionStepItem item) {
        switch (type) {
            case 1:
                //锅体动作
                gtdzPaser(item, item.getId());
                break;
            case 2:
                //固体添加
                jGtPaser(item, item.getId());
                break;
            case 3:
                //液体添加
                ytdcPaser(item);
                break;
            default:

        }
    }


    /**
     * 锅体动作
     *
     * @param item
     */
    private void gtdzPaser(ActionStepItem item, int position) {
        Log.e(TAG, "点击:" + item.getName());
        switch (item.getName()) {
            case Constant.ACTION_NAME_TZJR: //停止加热
            case Constant.ACTION_NAME_TZJB://停止搅拌
            case Constant.ACTION_NAME_GSGZ://洗锅
            case Constant.ACTION_NAME_GTFJG://洗锅
                sendCmd(getOperator(item.getName(), 0, 0));
                break;
            case Constant.ACTION_NAME_XG://洗锅
            case Constant.ACTION_NAME_DC://倒菜
            case Constant.ACTION_NAME_DKGZ://倒菜
            case Constant.ACTION_NAME_DS://倒菜
                sendCmd(getOperator(item.getName(), 255, 255));
                break;
            case Constant.ACTION_NAME_KQJR:
//                开始加热
                powerSelectDialog.showDialog(item);
//                doubleDialogShow("输入档位(1-8)", "输入温度(20-130)℃", item.getId(), "档位:", "温度:");
                break;
            case Constant.ACTION_NAME_KSJB:
                //开始搅拌
                jbSelectDialog.showDialog(item);
//                doubleDialogShow("输入档位(1-9)", "1反转 2正转", item.getId(), "转速:", "方向:");
                break;
            case Constant.ACTION_NAME_JSC:
                //加食材
                singleDialogShow("编号（1-4）",item.getId(),"格子编号");
//                doubleDialogShow("格子序号", "格子打开的时间", item.getId(), "序号:", "时长:");
                break;
            case Constant.ACTION_NAME_FW:
                //复位
                sendCmd(getOperator(item.getName(), 1, 1));
                break;
            case Constant.ACTION_NAME_CCJD:
                //炒菜
                powerCcjdDialog.showDialog(item);
//                singleDialogShow("锅体斜度，数值(1、2)", item.getId(), "斜度:");
                break;
            case Constant.ACTION_NAME_JC:
                //手动加菜
                sendCmd(getOperator(item.getName(), 1, 1));
                break;
            case Constant.ACTION_NAME_PK:
                //液体管道排空
                singleDialogShow("排空时长/秒", item.getId(), "时长:");
                break;
            case Constant.ACTION_NAME_JGG:
                //液体管道排空
                singleDialogShow("1:加上盖子 2:拿走盖子", item.getId(), "动作:");
                break;
        }
    }

    /**
     * 显示双输入的弹窗
     *
     * @param hint1
     * @param hint2
     * @param id
     * @param tips1
     * @param tips2
     */
    private void doubleDialogShow(String hint1, String hint2, int id, String tips1, String tips2) {
        Log.e(TAG, "hint1=" + hint1 + " hint2=" + hint2);
        doubleInputDialog.setHintMsg(hint1, hint2);
        doubleInputDialog.setTips(tips1, tips2);
        doubleInputDialog.showDialog(id);
    }

    private Operator getOperator(String name, int value1, int value2) {
        Operator operator = new Operator();
        operator.setName(name);
        operator.setValue(value1);
        operator.setValue1(value2);
        if (TextUtils.equals(name, Constant.ACTION_NAME_KSJB)
                || TextUtils.equals(name, Constant.ACTION_NAME_TZJB)) {
            operator.setValue(value2);
            operator.setValue1(value1);
        }
        return operator;
    }

    /**
     * 显示单个输入的弹窗
     *
     * @param hint
     * @param id
     * @param tips
     */
    private void singleDialogShow(String hint, int id, String tips) {
        singleInputDialog.setTips(tips);
        singleInputDialog.setHintMsg(hint);
        singleInputDialog.showDialog(id);
    }

    /**
     * 液体动作
     *
     * @param item
     */
    private void ytdcPaser(ActionStepItem item) {
//        doubleInputDialog.setHintMsg("输入打开时长", "输入调料重量");
//        doubleInputDialog.setTips("时长", "重量");
//        doubleInputDialog.showDialog(item.getId());
        singleInputDialog.setHintMsg( "输入调料重量");
        singleInputDialog.setTips( "重量");
        singleInputDialog.showDialog(item.getId());
    }

    /**
     * 加固体动作
     *
     * @param item
     */
    private void jGtPaser(ActionStepItem item, int position) {
//        singleDialogShow("打开时长", item.getId(), "时长:");
        doubleInputDialog.setHintMsg("输入打开时长", "输入调料重量");
        doubleInputDialog.setTips("时长", "重量");
        doubleInputDialog.showDialog(item.getId());
    }

    private void sendCmd(Operator operator) {
        showDialog();
        EventBus.getDefault().post(operator, Constant.ACTION_CMD_INFO_DEBUG);
        OperatorAutoHandle.getInstance(null, null, "")
                .payTips(operator);
    }

    /**
     * 吐司弹窗
     *
     * @param msg
     */
    private void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == WHAT_CANCEL_DIALOG) {
            if (loadingDialog != null) {
                loadingDialog.close();
            }
        }
        return false;
    }

    /**
     * 显示加载动画
     */
    private void showDialog() {
        loadingDialog.show();
        handler.removeMessages(WHAT_CANCEL_DIALOG);
        handler.sendEmptyMessageDelayed(WHAT_CANCEL_DIALOG, 1000);
    }

    @Override
    public void SingleDialogInputResult(String value, int id) {
        Log.e(TAG, "value=" + value + " id=" + id);
        ActionStepItem actionStepItem = actionStepItemDao.queryForId(id);
        Log.e("qindaji", JsonHelper.toJson(actionStepItem));
        if (actionStepItem == null) {
            showToast("数据为空");
            return;
        }
        if(actionStepItem.getType()==Constant.ACTION_STEP_JYT){
            yttlAction(actionStepItem, 0, getStringValue(value));
        }else {
            sendCmd(getOperator(actionStepItem.getName(), getStringValue(value), getStringValue(value)));
        }
    }

    /**
     * 转换值
     *
     * @param value
     * @return
     */
    private int getStringValue(String value) {
        int temp = 0;
        try {
            temp = Integer.parseInt(value);
        } catch (Exception e) {
            showToast("数据解析异常");
        }
        return temp;
    }

    @Override
    public void doubleDialogInputResult(int value1, int value2, int id) {
        Log.e(TAG, "value1=" + value1 + " value2=" + value2 + " id=" + id);
        ActionStepItem actionStepItem = actionStepItemDao.queryForId(id);
        Log.e("qindaji", JsonHelper.toJson(actionStepItem));
        if (actionStepItem == null) {
            showToast("数据为空");
            return;
        }
        switch (actionStepItem.getType()) {
            case Constant.ACTION_STEP_GDZ:
                handleGtDZ(actionStepItem, value1, value2);
                break;
            case Constant.ACTION_STEP_JGT:
                gttlAction(actionStepItem, value1, value2);
                break;
            case Constant.ACTION_STEP_JYT:
                yttlAction(actionStepItem, value1, value2);
                break;
        }
    }

    private void gttlAction(ActionStepItem actionStepItem, int value1, int value2) {
        Log.e(TAG, "固体调料:" + JsonHelper.toJson(actionStepItem) + " value1=" + value1 + " value2=" + value2);
        Operator operator = getOperator(actionStepItem.getName(), value1, value2);
        operator.setNum(actionStepItem.getSerialNo());
        sendCmd(operator);
    }

    private void yttlAction(ActionStepItem actionStepItem, int value1, int value2) {
        Log.e(TAG, "液体调料:" + JsonHelper.toJson(actionStepItem) + " value1=" + value1 + " value2=" + value2);
        Operator operator = getOperator(actionStepItem.getName(), value1, value2);
        operator.setNum(actionStepItem.getSerialNo());
        sendCmd(operator);
    }


    private void handleGtDZ(ActionStepItem actionStepItem, int value1, int value2) {
        Log.e(TAG, "name=" + actionStepItem.getName() + " value1=" + value1 + " value2=" + value2);
        if (checkValueLimit(actionStepItem, value1, value2)) {
            sendCmd(getOperator(actionStepItem.getName(), value1, value2));
        }
    }

    private boolean checkValueLimit(ActionStepItem actionStepItem, int value1, int value2) {
        Log.e(TAG, "checkValueLimit:" + actionStepItem.getName() + " value1=" + value1 + " value2=" + value2);
        if (TextUtils.equals(actionStepItem.getName(), Constant.ACTION_NAME_KQJR) && value2 > HOT_TEMP_MAX) {
            showToast("线盘温度不能超过100度");
            return false;
        }
        if (TextUtils.equals(actionStepItem.getName(), Constant.ACTION_NAME_KQJR) && value1 > 8) {
            showToast("加热党委不能超过8档");
            return false;
        }

        return true;
    }


    @Override
    public void hotModelUtilCallback(int power, int temp, byte error) {
        tvPower.setText(Integer.toString(power));
        tvTemp.setText(Integer.toString(temp));
        tvError.setText(hotModelUtil.getErrorString(error));
    }



    @Override
    public void onItemClickResult(ActionStepItem actionStepItem,int result) {
        Log.e(TAG, "onItemClickResult 档位:"+result);
        try {
            handleGtDZ( actionStepItem, result, Constant.HOT_TEMP_MAX-1);
        }catch (Exception e){
            showToast(e.getMessage());
        }
    }

    @Override
    public void onJbItemClickResult(ActionStepItem actionStepItem, int result, int direct) {
        try {
            Log.e(TAG, "onJbItemClickResult 速度:"+result+" 方向:"+direct);
            sendCmd(getOperator(actionStepItem.getName(), result, direct));
        }catch (Exception e){
            showToast(e.getMessage());
        }
    }

    @Override
    public void onItemCcjdResult(ActionStepItem actionStepItem, int result) {
        Log.e(TAG, "onItemCcjdResult 角度:"+result);
        sendCmd(getOperator(actionStepItem.getName(), result, result));
    }
}
